package com.api.customization.huangwm.formmode.lims;

import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;

import com.customization.huangwm.utils.LogTool;

import weaver.conn.RecordSet;
import weaver.conn.RecordSetTrans;

import com.alibaba.fastjson.JSONObject;
import com.customization.huangwm.utils.DateTools;
import com.engine.common.util.ParamUtil;
import weaver.general.BaseBean;

/**
 * @author Huangwm
 * @description
 */
public class UpdateLimsProcessApi extends BaseBean {

    private LogTool log = new LogTool("/log/Lims/huangwm/api/UpdateLimsProcessApi", false);

    private String TableName_CY = getPropValue("LIMS", "formtable1");//采樣流程
    private String TableName_HY = getPropValue("LIMS", "formtable2");//化驗單
    private String TableName_YSSY = getPropValue("LIMS", "formtable3");//驗水試壓
    private String tableKey_HY = "lab_samplenum";//化验单唯一值

    @POST
    @Path("/updateLimsToEAP")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> updateLimsToEAP(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        log.writeLog("updateLimsToEAP--->进入方法 " + new DateTools().getCurrentTimes());

        Map<String, Object> apiResult = new HashMap<String, Object>();
        apiResult.put("apiStatus", true);
        if (TableName_CY.isEmpty()) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "未獲取到EAP配置文件LIMS.properties中的formtable1");
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        try {
            Map<String, Object> requestParams = ParamUtil.request2Map(request);
            log.writeLog("-------传入参数------");
            log.writeLog(JSONObject.toJSONString(requestParams));
            if (!requestParams.containsKey("datajson")) {
                apiResult.put("apiStatus", false);
                apiResult.put("msg", "参数未找到datajson节点");
                log.writeLog(JSONObject.toJSONString(apiResult));
                log.writeLog("updateLimsToEAP--->结束方法");
                return apiResult;
            }
            Map<String, Object> datajson = JSONObject.parseObject(JSONObject.toJSONString(requestParams.get("datajson"))).getJSONObject("datajson");
            log.writeLog(JSONObject.toJSONString(datajson));
            if (!datajson.containsKey("data")) {
                apiResult.put("apiStatus", false);
                apiResult.put("msg", "参数datajson中未找到data节点");
                log.writeLog(JSONObject.toJSONString(apiResult));
                log.writeLog("updateLimsToEAP--->结束方法");
                return apiResult;
            }
            List<Map<String, Object>> data = (List<Map<String, Object>>) datajson.get("data");
            for (int i = 0; i < data.size(); i++) {
                Map<String, Object> data_ = data.get(i);
                if (!data_.containsKey("operationwriteLog")) {
                    apiResult.put("apiStatus", false);
                    apiResult.put("msg", "参数datajson>data[" + (i + 1) + "]中未找到operationwriteLog节点");
                    log.writeLog(JSONObject.toJSONString(apiResult));
                    log.writeLog("updateLimsToEAP--->结束方法");
                    return apiResult;
                }
                if (!data_.containsKey("mainTable")) {
                    apiResult.put("apiStatus", false);
                    apiResult.put("msg", "参数datajson>data[" + (i + 1) + "]中未找到mainTable节点");
                    log.writeLog(JSONObject.toJSONString(apiResult));
                    log.writeLog("updateLimsToEAP--->结束方法");
                    return apiResult;
                }
                if (!data_.containsKey("detail1")) {
                    apiResult.put("apiStatus", false);
                    apiResult.put("msg", "参数datajson>data[" + (i + 1) + "]中未找到detail1节点");
                    log.writeLog(JSONObject.toJSONString(apiResult));
                    log.writeLog("updateLimsToEAP--->结束方法");
                    return apiResult;
                }
                Map<String, Object> operationwriteLog = (Map<String, Object>) data.get(i).get("operationwriteLog");
                Map<String, Object> mainTable = (Map<String, Object>) data.get(i).get("mainTable");
                List<Map<String, Object>> detail1 = (List<Map<String, Object>>) data.get(i).get("detail1");

                if (!mainTable.containsKey("LimsNo")) {
                    apiResult.put("apiStatus", false);
                    apiResult.put("msg", "参数datajson>data[" + (i + 1) + "]>mainTable中未找到LimsNo");
                    log.writeLog(JSONObject.toJSONString(apiResult));
                    log.writeLog("updateLimsToEAP--->结束方法");
                    return apiResult;
                } else {
                    String limsno = mainTable.get("LimsNo").toString();
                    String operator = operationwriteLog.get("operator").toString();

                    String sql1 = "select t.requestid,t.id,wr.creater,hr.workcode,wr.currentnodetype from " + TableName_CY + " t " +
                            "\n left join workflow_requestbase wr on t.requestid=wr.requestid " +
                            "\n left join HrmResource hr on hr.id=wr.creater " +
                            "\n where LimsNo='" + limsno + "'";
                    RecordSet rs1 = new RecordSet();
                    rs1.execute(sql1);
                    if (rs1.next()) {
                        String workcode = rs1.getString("workcode");
                        String currentnodetype = rs1.getString("currentnodetype");
                        if (!currentnodetype.equals("0")) {
                            apiResult.put("apiStatus", false);
                            apiResult.put("msg", "LimsNo[" + limsno + "]对应系统中的单据已经提交,禁止更新!");
                            log.writeLog(JSONObject.toJSONString(apiResult));
                            log.writeLog("updateLimsToEAP--->结束方法");
                            return apiResult;
                        }
                        if (workcode.equals(operator)) {
                            if (detail1 == null || detail1.size() <= 0) {
                                apiResult.put("apiStatus", false);
                                apiResult.put("msg", "参数datajson>data[" + (i + 1) + "]>detail1节点参数为空");
                                log.writeLog(JSONObject.toJSONString(apiResult));
                                log.writeLog("updateLimsToEAP--->结束方法");
                                return apiResult;
                            }
                            String id = rs1.getString("id");
                            RecordSet rs2 = new RecordSet();
                            RecordSetTrans rst1 = new RecordSetTrans();
                            rst1.setAutoCommit(false);
                            RecordSetTrans rst2 = new RecordSetTrans();
                            rst2.setAutoCommit(false);
                            //1 更新明细表 如果有多余则新增
                            boolean result1 = true;
                            boolean result2 = true;
                            int up = 0;
                            int in = 0;
                            for (int j = 0; j < detail1.size(); j++) {
                                Map<String, String> detail_data = (Map<String, String>) detail1.get(i).get("data");
                                String SampleNo = detail_data.get("SampleNo");
                                String SamplingLocation = detail_data.get("SamplingLocation");
                                String sampleuser = detail_data.get("sampleuser");
                                String simpleid = detail_data.get("simpleid");//明细更新的判断条件 存在即更新 不存在则新增
                                if (simpleid.isEmpty()) {
                                    apiResult.put("nullMsg", "本次更新存在为空的simpleid,请查看参数");
                                } else {
                                    rs2.execute("select id  from " + TableName_CY + "_dt1 where simpleid='" + simpleid + "'");
                                    if (rs2.next()) {
                                        try {
                                            String up1 = "update " + TableName_CY + "_dt1 set SamplingLocation='" + SamplingLocation + "',SampleNo='" + SampleNo + "',SampleUser=(select id from hrmresource where workcode='" + sampleuser + "') where simpleid='" + simpleid + "'";
                                            result1 = rst1.execute(up1);
                                            apiResult.put("update_" + simpleid, result1);
                                            up++;
                                        } catch (Exception e) {
                                            apiResult.put("update_" + simpleid, "采样明细[" + simpleid + "]更新存在异常;" + e.getMessage());
                                        }
                                    } else {
                                        try {
                                            String insert1 = "insert into "+TableName_CY+"_dt1(mainid,SamplingLocation,SampleNo,simpleid,SampleUser)values(" + id + ",'" + SamplingLocation + "','" + SampleNo + "','" + simpleid + "',(select id from hrmresource where workcode='" + sampleuser + "'))";
                                            result2 = rst2.execute(insert1);
                                            apiResult.put("insert_" + simpleid, result2);
                                            in++;
                                        } catch (Exception e) {
                                            apiResult.put("update_" + simpleid, "采样明细[" + simpleid + "]插入存在异常;" + e.getMessage());
                                        }
                                    }
                                }
                            }
                            apiResult.put("update", result1);
                            apiResult.put("insert", result2);
                            if (result1 && result2) {
                                apiResult.put("apiStatus", true);
                                apiResult.put("msg", "采样记录TaskId[" + limsno + "]更新成功;本次更新行数" + up + ",新增行数" + in);
                                rst1.commit();
                                rst2.commit();
                            } else {
                                if (!result1) {
                                    apiResult.put("apiStatus", false);
                                    apiResult.put("msg", "采样明细更新失败;请联系OA管理员查看日志");
                                    rst1.rollback();
                                }
                                if (!result2) {
                                    apiResult.put("apiStatus", false);
                                    apiResult.put("msg", "采样明细插入失败;请联系OA管理员查看日志");
                                    rst2.rollback();
                                }
                            }
                        } else {
                            apiResult.put("apiStatus", false);
                            apiResult.put("msg", "参数datajson>data[" + (i + 1) + "]>operationwriteLog中的operator[" + operator + "]跟系统数据不符(" + workcode + ")");
                        }
                    } else {
                        apiResult.put("apiStatus", false);
                        apiResult.put("msg", "LimsNo[" + limsno + "]未找到对应的数据");
                    }
                }
            }
        } catch (Exception e) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "接口异常;" + e.getMessage());
        }
        log.writeLog(JSONObject.toJSONString(apiResult));
        log.writeLog("updateLimsToEAP--->结束方法");
        return apiResult;
    }

    @POST
    @Path("/receiveAssayResults")
    @Produces(MediaType.APPLICATION_JSON)
    //接收化驗結果更新至化驗單
    public Map<String, Object> receiveAssayResults(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        //public Map<String, Object> receiveAssayResults(Map<String, Object> requestParams) {
        log.writeLog("receiveAssayResults--->进入方法 " + new DateTools().getCurrentTimes());

        Map<String, Object> apiResult = new HashMap<String, Object>();
        apiResult.put("apiStatus", true);
        if (TableName_HY.isEmpty()) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "未獲取到EAP配置文件LIMS.properties中的formtable2");
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        Map<String, Object> requestParams = ParamUtil.request2Map(request);
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            apiResult.put("msg", "缺少參數datas");
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        Map<String, Object> datas = new HashMap<>();
        try {
            datas = JSONObject.parseObject(requestParams.get("datas").toString());
        } catch (Exception e) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }

        if (!datas.containsKey("OA_key")) {
            apiResult.put("msg", "datas中缺少必要參數OA_key");
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        String OA_key = datas.get("OA_key").toString();
        int billid = checkRequestid(OA_key,tableKey_HY);
        if (OA_key.isEmpty() || billid == 0) {
            apiResult.put("msg", "OA_key为空或非化學藥品交收單數據id OA_key=" + OA_key);
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        if (!datas.containsKey("result")) {
            apiResult.put("msg", "datas中缺少必要參數result");
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        List<Map<String, String>> result = new ArrayList<>();
        try {
            //result = (List<Map<String,String>>) datas.get("result");
            result = (List<Map<String, String>>) JSONObject.parse(datas.get("result").toString());
        } catch (Exception e) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "從datas參數中轉化result数组異常 " + e.getMessage());
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        log.writeLog("接收参数");
        log.writeLog(JSONObject.toJSONString(datas));

        List<List<Object>> setList = new ArrayList<>();
        List<String> limsFields = new ArrayList<>();
        for (Map<String, String> data : result) {
            log.writeLog(JSONObject.toJSONString(data));
            List<Object> param = new ArrayList<>();
            param.add(billid);
            param.add(data.get("sample_id"));
            param.add(data.get("sample_index"));
            param.add(data.get("sample_name"));
            param.add(data.get("collect_date").replace("/", "-"));
            param.add(data.get("item_id"));
            param.add(data.get("item_name"));
            param.add(data.get("unit_name"));
            param.add(data.get("result"));
            param.add(data.get("ext_std"));
            param.add(data.get("quality"));
            setList.add(param);
            //返回以&作为分隔的字段对应关系
            limsFields.add(data.get("item_id") + "&" + data.get("result"));
        }

        //拼接更新主表字段信息SQL
        Map<String, String> FieldContras = new HashMap<>();
        RecordSet rs = new RecordSet();
        //查询lims字段对应的主表字段关系
        rs.execute("select * from uf_limsFieldContras");
        while (rs.next()) {
            FieldContras.put(rs.getString("limsField"), rs.getString("eapField"));
        }
        log.writeLog("lims字段对照");
        log.writeLog(JSONObject.toJSONString(FieldContras));

        log.writeLog("参数字段："+limsFields.toString());
        String mainSql = "update " + TableName_HY + " set requestid=requestid ";
        for (String field : limsFields) {
            mainSql += " ," + FieldContras.get(field.split("&")[0]) + "='" + field.split("&")[1] + "' ";
        }
        mainSql += " where "+tableKey_HY+"='" + OA_key+"'";
        boolean umain = false;
        String sql = "insert into " + TableName_HY + "_dt1" + "(mainid,sampleid,sampleindex,samplename,colletname,itemid,itemname,unitname,result,extstd,quality)"
                + "values(?,?,?,?,?,?,?,?,?,?,?)";
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        try {
            umain = rst.execute(mainSql);
        } catch (Exception e) {
            e.printStackTrace();
            rst.rollback();
            apiResult.put("msg", "更新化驗單主表執行SQL異常 \n" + mainSql + " \n " + e.getMessage());
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        if (!umain) {
            apiResult.put("msg", "更新化驗單主表失敗 \n" + mainSql);
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        try {
            rst.executeBatchSql(sql, setList);
        } catch (Exception e) {
            e.printStackTrace();
            rst.rollback();
            apiResult.put("msg", "接收化驗結果更新至化驗單明細執行SQL異常 \n" + e.getMessage());
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        rst.commit();

        log.writeLog(JSONObject.toJSONString(apiResult));
        log.writeLog("receiveAssayResults--->結束方法");
        return apiResult;
    }

    public int checkRequestid(String OA_key,String tableKey_HY) {
        int id = 0;
        RecordSet rs = new RecordSet();
        rs.execute("select id from " + TableName_HY + " where "+tableKey_HY+"='" + OA_key+"'");
        if (rs.next()) id = rs.getInt("id");
        return id;
    }

    public int checkRequestid2(String OA_key,String tableKey) {
        int id = 0;
        RecordSet rs = new RecordSet();
        rs.execute("select id from " + TableName_YSSY + " where "+tableKey+"='" + OA_key+"'");
        if (rs.next()) id = rs.getInt("id");
        return id;
    }

    @POST
    @Path("/receivePipelineResults")
    @Produces(MediaType.APPLICATION_JSON)
    public Map<String, Object> receivePipelineResults(@Context HttpServletRequest request, @Context HttpServletResponse response) {
        log.writeLog("receivePipelineResults--->进入方法 " + new DateTools().getCurrentTimes());

        Map<String, Object> apiResult = new HashMap<String, Object>();
        apiResult.put("apiStatus", true);
        if (TableName_YSSY.isEmpty()) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "未獲取到EAP配置文件LIMS.properties中的formtable3");
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receiveAssayResults--->結束方法");
            return apiResult;
        }
        Map<String, Object> requestParams = ParamUtil.request2Map(request);
        log.writeLog(JSONObject.toJSONString(requestParams));
        if (!requestParams.containsKey("datas")) {
            apiResult.put("msg", "缺少參數datas");
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receivePipelineResults--->結束方法");
            return apiResult;
        }
        Map<String, Object> datas = new HashMap<>();
        try {
            datas = JSONObject.parseObject(requestParams.get("datas").toString());
        } catch (Exception e) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "從參數中轉化datas異常 " + e.getMessage());
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receivePipelineResults--->結束方法");
            return apiResult;
        }

        if (!datas.containsKey("OA_key")) {
            apiResult.put("msg", "datas中缺少必要參數OA_key");
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receivePipelineResults--->結束方法");
            return apiResult;
        }
        String OA_key = datas.get("OA_key").toString();
        int billid = checkRequestid2(OA_key,"requestid");
        if (OA_key.isEmpty() || billid == 0) {
            apiResult.put("msg", "OA_key为空或非驗水試壓單數據id OA_key=" + OA_key);
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receivePipelineResults--->結束方法");
            return apiResult;
        }
        if (!datas.containsKey("result")) {
            apiResult.put("msg", "datas中缺少必要參數result");
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receivePipelineResults--->結束方法");
            return apiResult;
        }
        List<Map<String, String>> result = new ArrayList<>();
        try {
            //result = (List<Map<String,String>>) datas.get("result");
            result = (List<Map<String, String>>) JSONObject.parse(datas.get("result").toString());
        } catch (Exception e) {
            apiResult.put("apiStatus", false);
            apiResult.put("msg", "從datas參數中轉化result数组異常 " + e.getMessage());
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receivePipelineResults--->結束方法");
            return apiResult;
        }

        List<List<Object>> setList = new ArrayList<>();
        for (Map<String, String> data : result) {
            List<Object> param = new ArrayList<>();
            param.add(billid);
            param.add(data.getOrDefault("00_21_154", "0").toString());
            param.add(data.getOrDefault("00_21_126", "0").toString());
            param.add(data.getOrDefault("00_21_157", "0").toString());
            setList.add(param);
        }
        log.writeLog(JSONObject.toJSONString(setList));

        String sql = "insert into " + TableName_YSSY + "_dt5" + "(mainid,zdntu,xjzs,zdcgj)"
                + "values(?,?,?,?)";
        RecordSetTrans rst = new RecordSetTrans();
        rst.setAutoCommit(false);
        try {
            rst.executeBatchSql(sql, setList);
        } catch (Exception e) {
            e.printStackTrace();
            rst.rollback();
            apiResult.put("msg", "接收驗水試壓結果更新至單據明細執行SQL異常 \n" + e.getMessage());
            apiResult.put("apiStatus", false);
            log.writeLog(JSONObject.toJSONString(apiResult));
            log.writeLog("receivePipelineResults--->結束方法");
            return apiResult;
        }
        rst.commit();

        return apiResult;
    }

}
